package com.mediatek.factorymode.version;

import com.mediatek.factorymode.R;
import com.mediatek.factorymode.itemutils.Item;
import com.mediatek.factorymode.itemutils.ItemAdapter;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ListView;
import com.mediatek.factorymode.Utils;
import android.os.SystemProperties;

import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.PhoneConstants;
import android.telephony.TelephonyManager;
import android.telephony.TelephonyManager.MultiSimVariants;
import android.content.Context;
import android.bluetooth.BluetoothAdapter;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import android.util.Log;
import android.widget.SimpleAdapter;
import android.widget.ArrayAdapter;
import android.view.ViewGroup;
import android.view.LayoutInflater;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

public class version extends Activity implements OnClickListener {
	private ListView infolist;
	private SharedPreferences mSp;

	private TextView mBtFailed;
	private TextView mBtOk;
	private static final String FILENAME_PROC_VERSION = "/proc/version";

    private final String bb_chip_i =              ":"+SystemProperties.get("ro.board.platform");          
    private final String ms_board_i =             ":"+SystemProperties.get("ro.product.name");            
    private final String imei_i =                 ":"+getMtkImei();           
    private final String modem_version_i=         ":"+SystemProperties.get("gsm.version.baseband");       
    private final String barCode_i =              ":"+Build.getSerial();
    private final String build_tiem_i=            ":"+SystemProperties.get("ro.build.date");
    private final String kernel_version_i=        ":"+getFormattedKernelVersion();
    private final String android_version_i=       ":"+SystemProperties.get("ro.build.version.release");
    private final String sw_version_i=            ":"+SystemProperties.get("ro.build.display.id");
    private final String custom_build_version_i=  ":"+SystemProperties.get("ro.custom.build.version");
    //private final String wifiAddress_i =          ":"+getWifiMac();
    private final String btAddress_i =            ":"+getBtMac();

	private String[] name = {
		"BB Chip",			
		"MS Board",		
		"IMEI",			
		"Modem Version",		
		"Bar code",		
		"Build Time",
		"kernel Version",
		"Android Version",
		"SW Version",
		"Custom Build Version",
		//"Wi-Fi MAC address",
		"Bluetooth address"
	};

    private String[] info ={
        bb_chip_i,           
        ms_board_i,          
        imei_i,               
        modem_version_i,      
        barCode_i,           
        build_tiem_i,        
        kernel_version_i,    
        android_version_i,     
        sw_version_i,          
        custom_build_version_i,
        //wifiAddress_i,       
        btAddress_i         
    };
   
	public void onClick(View paramView) {
		SharedPreferences localSharedPreferences = this.mSp;
		// int i = 2131230850;
		int j = paramView.getId();
		int k = this.mBtOk.getId();
		int kk = this.mBtFailed.getId();
		if (j == k) {
			Utils.SetPreferences(this, localSharedPreferences,
					R.string.version, "success");
			Utils.putInt(this, "Version", 1);
			finish();
		}
		if (j == kk) {
			Utils.SetPreferences(this, localSharedPreferences,
					R.string.version, "failed");
			Utils.putInt(this, "Version", 0);
			finish();
		}

	}

	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.version);
		SharedPreferences localSharedPreferences = getSharedPreferences(
				"FactoryMode", 0);
		this.mSp = localSharedPreferences;

		infolist = (ListView)findViewById(R.id.infolist);
		TextView localTextView1 = (TextView) findViewById(R.id.bt_ok);
		this.mBtOk = localTextView1;
		this.mBtOk.setOnClickListener(this);
		TextView localTextView2 = (TextView) findViewById(R.id.bt_failed);
		this.mBtFailed = localTextView2;
		this.mBtFailed.setOnClickListener(this);

		initList();
	}

    private void initList() {
        List<Item> list = new ArrayList<>();
        for (int i = 0; i < name.length; i++) {
            Item item = new Item(name[i], info[i]);
            list.add(item);
        }
        list.add(new Item("Wi-Fi MAC address", getWifiMac()));//wifi mac
        ItemAdapter itemAdapter = new ItemAdapter(version.this, R.layout.version_list, list);
        infolist.setAdapter(itemAdapter);
    }


    public static String getFormattedKernelVersion() {
        try {
            return formatKernelVersion(readLine(FILENAME_PROC_VERSION));

        } catch (IOException e) {
            Log.e("chl",
                "IO Exception when getting kernel version for Device Info screen",e);
            return "Unavailable";
        }
    }

    private static String readLine(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename), 256);
        try {
            return reader.readLine();
        } finally {
            reader.close();
        }
    }

    public static String formatKernelVersion(String rawKernelVersion) {
        final String PROC_VERSION_REGEX =
            "Linux version (\\S+) " + /* group 1: "3.0.31-g6fb96c9" */
            "\\((\\S+?)\\) " +        /* group 2: "x@y.com" (kernel builder) */
            "(?:\\(gcc.+? \\)) " +    /* ignore: GCC version information */
            "(#\\d+) " +              /* group 3: "#1" */
            "(?:.*?)?" +              /* ignore: optional SMP, PREEMPT, and any CONFIG_FLAGS */
            "((Sun|Mon|Tue|Wed|Thu|Fri|Sat).+)"; /* group 4: "Thu Jun 28 11:02:39 PDT 2012" */

        Matcher m = Pattern.compile(PROC_VERSION_REGEX).matcher(rawKernelVersion);
        if (!m.matches()) {
            Log.e("chl", "Regex did not match on /proc/version: " + rawKernelVersion);
            return "Unavailable";
        } else if (m.groupCount() < 4) {
            Log.e("chl", "Regex match on /proc/version only returned " + m.groupCount()
                    + " groups");
            return "Unavailable";
        }
        return m.group(1); //lxf++
        //return m.group(1) + "\n" +                 // 3.0.31-g6fb96c9
        //    m.group(2) + " " + m.group(3) + "\n" + // x@y.com #1
        //    m.group(4);                            // Thu Jun 28 11:02:39 PDT 2012
    }
	
    private String getMtkImei() {
    	String imei = "";
    	if(!Utils.mIsDsds()){
    		return getImei(1);
    	}else{
    		return getImei(1)+"\n"+":"+getImei(2);	
    	}
    }

	private int getDefaultDataPhoneId(int slot) {
        int simId = PhoneConstants.SIM_ID_1;
        if (true) {
            if (slot == 1) {
                simId = PhoneConstants.SIM_ID_1;
            } else if (slot == 2) {
                simId = PhoneConstants.SIM_ID_2;
            }
        }
        return simId;
    }

    private String getImei(int slot){
        String imei = null;
        Phone mPhone = null;
        if (true) {
            if(slot == 1){
                mPhone = PhoneFactory.getPhone(getDefaultDataPhoneId(1));
                imei = mPhone.getDeviceId();
            }else if(slot == 2){
                mPhone = PhoneFactory.getPhone(getDefaultDataPhoneId(2));
                imei = mPhone.getDeviceId();
            }
        }else{
            mPhone = PhoneFactory.getPhone(getDefaultDataPhoneId(1));
            imei = mPhone.getDeviceId();
        }
        return imei;
    }

    private String getBtMac(){
    	BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    	String btAddress = null;
    	if (bluetooth != null){
    		btAddress = bluetooth.isEnabled() ? bluetooth.getAddress() : null;
    	}
    	return btAddress;
    }

    private String getWifiMac(){
    	String wifiAddress = null;	
    	WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    	WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
        wifiAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
        return wifiAddress;
    }
}
